//
//  RDTextDataParser.m
//  eCourseApp
//
//  Created by 飞猪 on 2018/8/26.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RDTextDataParser.h"

@implementation RDTextDataParser

- (void)parseChapterFromBook:(NSString *)path completeHandler:(ChapterBlock)chapterBlock {
  
  // 0. 整本书籍加载到内存
  NSURL *url = [NSURL fileURLWithPath:path];
  NSString *content = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
  
  // 1.
  NSMutableArray<RDChapterModel *> *models = [NSMutableArray array];
  NSMutableArray<NSString *> *titles = [NSMutableArray array];
  
  // 异步处理
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
    // 保存在本地沙盒中
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // 根据path获取书名
    NSString *fileName = [[[path lastPathComponent] componentsSeparatedByString:@"."] firstObject];
    //
    NSString *bookPath = [NSString stringWithFormat:@"%@/%@", document, fileName];
    
    BOOL res = [[NSFileManager defaultManager] fileExistsAtPath:bookPath];
    if (!res) {
      [[NSFileManager defaultManager] createDirectoryAtPath:bookPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    // 匹配章节标题
    NSArray<NSTextCheckingResult *> *results = [self doTitleMatchWith:content];
    
    if (results.count == 0) {
      
      RDChapterModel *model = [[RDChapterModel alloc] init];
//      model.chapterIndex = 1;
      model.path = path;
      if (chapterBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
          chapterBlock(@[], @[model]);
        });
      }
    }
    else {
      
      NSInteger endIndex = 0;
      for(NSInteger i = 0; i < results.count; ++i) {
        
        NSTextCheckingResult *result = [results objectAtIndex:i];
      
        NSInteger startIndex = result.range.location;
        endIndex = result.range.length;
        
        NSString *currentTitle = [content substringWithRange:NSMakeRange(startIndex, endIndex)];
        [titles addObject:currentTitle];
        
        NSString *chapterPath = [NSString stringWithFormat:@"%@/chapter%@.txt", bookPath, [@(i) stringValue]];
        
        RDChapterModel *model = [[RDChapterModel alloc] init];
//        model.chapterIndex = i + 1;
//        model.title = currentTitle;
        model.path = chapterPath;
        [models addObject:model];
        
        BOOL res = [[NSFileManager defaultManager] fileExistsAtPath:chapterPath];
        if (res) {
          continue;
        }
        
        NSInteger endLoaction = 0;
        if (i == results.count - 1) {
          endLoaction = content.length - 1;
        }
        else {
          endLoaction = results[i + 1].range.location - 1;
        }
        
        NSInteger startLocation = result.range.location;
        NSInteger length = endLoaction - startLocation;
        
        
        NSString *subString = [content substringWithRange:NSMakeRange(startLocation, length)];
        [subString writeToFile:chapterPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
      }

      dispatch_async(dispatch_get_main_queue(), ^{
        chapterBlock(titles, models);
      });
    }
  });
  
}

- (RDChapterModel *)parseChapterFromModel:(RDNETChapterModel *)chapterModel {
  
  if (!chapterModel) return nil;
  
  // 保存在本地沙盒中
  NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  // 根据path获取书名
  NSString *fileName = [chapterModel bookId];
  //
  NSString *bookPath = [NSString stringWithFormat:@"%@/%@", document, fileName];
  
  BOOL res = [[NSFileManager defaultManager] fileExistsAtPath:bookPath];
  if (!res) {
    [[NSFileManager defaultManager] createDirectoryAtPath:bookPath withIntermediateDirectories:YES attributes:nil error:nil];
  }

  NSString *chapterPath = [NSString stringWithFormat:@"%@/chapter%@.txt", bookPath, chapterModel.chId];

  RDChapterModel *model = [[RDChapterModel alloc] init];
  
  model.chName = chapterModel.chName;
  model.path = chapterPath;
  model.chId = chapterModel.chId;
  model.bookId = chapterModel.bookId;
  model.chCharge = chapterModel.chCharge;
  
  model.nextChId = chapterModel.nextChId;
  model.nextChCharge = chapterModel.nextChCharge;
  model.preChId = chapterModel.preChId;
  model.preChCharge = chapterModel.preChCharge;

  BOOL result = NO; //[[NSFileManager defaultManager] fileExistsAtPath:chapterPath];
  if (result) {
    NSLog(@"+++++++%@", model.chId);
    return model;
  }
  else {
    NSError *error = nil;
    BOOL resul = [chapterModel.chContent writeToFile:chapterPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (resul && !error) {
      NSLog(@"+++++++%@", model.chId);
      return model;
    }
    else {
      NSLog(@"+++++++%@", model.chId);
      return model;
    }
  }
  
}

- (NSAttributedString *)attributedStringFromChapterModel:(RDChapterModel *)chapter config:(RDConfiguration *)config {
  
  NSURL *tmpUrl = [NSURL fileURLWithPath:chapter.path];
  NSString *tmpString = [[NSString alloc] initWithContentsOfURL:tmpUrl encoding:NSUTF8StringEncoding error:nil];
  if (tmpString == nil) {
    return nil;
  }
  NSString *contentString = tmpString;
  
//  NSArray<NSTextCheckingResult *> *results = [self doTitleMatchWith:textString];
//  NSRange titleRange = NSMakeRange(0, 0);
//  if (results.count != 0) {
//    titleRange = [[results firstObject] range];
//  }
//
//  NSUInteger startLocation = titleRange.location;
//  NSUInteger endLocation = titleRange.length;
  
  // 标题 + 内容
//  NSString *titleString = [textString substringWithRange:NSMakeRange(startLocation, endLocation)];
//  NSString *contentString = [textString substringFromIndex:startLocation + endLocation];
  
  NSString *paraString = [self formatChapterString:contentString config:config];
  
  NSMutableParagraphStyle *paragraphStyleTitle = [[NSMutableParagraphStyle alloc] init];
  paragraphStyleTitle.alignment = NSTextAlignmentCenter;
  
  NSDictionary<NSAttributedStringKey, id> *dictTitle = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:21.f], NSParagraphStyleAttributeName : paragraphStyleTitle};
  
  NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  paragraphStyle.alignment = NSTextAlignmentJustified;
  paragraphStyle.lineHeightMultiple = config.lineHeightMutiplier;
  UIFont *font = [UIFont fontWithName:config.fontName size:config.fontSize];
  
  NSDictionary<NSAttributedStringKey, id> *dict = @{NSFontAttributeName : font,
                                            NSParagraphStyleAttributeName : paragraphStyle,
                                                    NSForegroundColorAttributeName : config.charColor};
  
//  NSString *newTitle = [NSString stringWithFormat:@"\n%@\n\n", titleString];
//  NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newTitle attributes:dictTitle];
  NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:paraString attributes:dict];
//  [attrString appendAttributedString:content];
  
//  return attrString;
  return content;
}

- (NSString *)formatChapterString:(NSString *)contentString config:(RDConfiguration *)config {
  
//  NSArray *paragraphArray = [contentString componentsSeparatedByString:@"\n"];
  NSArray *paragraphArray = [contentString componentsSeparatedByString:@"<br><br><br>"];
  NSMutableString *newParagraphString = @"".mutableCopy;
  
  for (int index = 0; index < paragraphArray.count; ++index) {
    NSString *paragraph = [paragraphArray objectAtIndex:index];
    
    NSString *string0 = [paragraph stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newParagraph = [string0 stringByReplacingOccurrencesOfString:@"\t" withString:@""];
//    NSString *newParagraph = [string1 tr] trimmingCharacters(in: .whitespacesAndNewlines)
    
    if (newParagraph.length != 0) {
      newParagraph = [NSString stringWithFormat:@"\t%@", newParagraph];
      if (index != paragraphArray.count - 1) {
        newParagraph = [NSString stringWithFormat:@"%@\n", newParagraph];
      }
      
      // 去除段落开头的空白 段落开头缩进2个字符
      newParagraph = [newParagraph stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
      newParagraph = [NSString stringWithFormat:@"\t%@", newParagraph];
      
      [newParagraphString appendString:newParagraph];
    }
  }

  return newParagraphString;
}

- (NSArray<NSTextCheckingResult *> *)doTitleMatchWith:(NSString *)content {
  
  NSString *pattern = @"第[ ]*[0-9一二三四五六七八九十百千]*[ ]*[章回].*";
  NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
  NSArray<NSTextCheckingResult *> *results = [regExp matchesInString:content options:NSMatchingReportCompletion range:NSMakeRange(0, content.length)];
  return results;
  
}

@end
